<template>
  <!-- 权限设置 -->
  <div class="permission">
    <el-card>
      <div class="btnbox">
        <el-button size="mini" type="primary" @click="openAdd(1, 0)">
          <i class="el-icon-edit">添加菜单</i>
        </el-button>
        <el-table :data="perList" row-key="id">
          <el-table-column label="菜单名称" prop="name"> </el-table-column>
          <el-table-column label="权限标识" prop="code"> </el-table-column>
          <el-table-column label="描述" prop="description"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                @click="openAdd(2, row.id)"
                v-if="row.type === 1"
                >添加权限点</el-button
              >
              <el-button type="text">查看api权限</el-button>
              <el-button type="text" @click="openEdit(row.id)">查看</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <mypanel
      ref="mypanel"
      :showDialog.sync="showDialog"
      @upDateData="getAllPer"
    ></mypanel>
  </div>
</template>

<script>
// 得到所有权限点数据
import { getAllPerApi, delPerApi } from "@/api/permission";
export default {
  name: "components",
  data() {
    return {
      // 权限列表
      perList: [],
      // 面板显示雨隐藏
      showDialog: false
    };
  },
  methods: {
    // 打开新增面板
    openAdd(type, pid) {
      this.showDialog = true;
      this.$refs.mypanel.getData(type, pid);
      // console.log(type);
      // console.log(pid);
    },
    // 删除权限
    async del(id) {
      try {
        // 询问是否删除
        await this.$confirm("是否删除数据", "提示");
        // 调用删除接口
        await delPerApi(id);
        // 提示删除成功
        this.$message.success("删除成功");
        // 更新数据
        this.getAllPer();
      } catch {}
    },
    // 得到所有权限点数据
    async getAllPer() {
      const res = await getAllPerApi();
      // console.log(res);
      // this.perList = res.data;
      this.perList = this.trunData(res.data, "0");
    },
    // 定义了一个树状结构数据的方法
    trunData(arr, pid) {
      const res = [];
      arr.forEach(item => {
        if (item.pid === pid) {
          const son = this.trunData(arr, item.id);
          if (son.length > 0) {
            item.children = son;
          }
          res.push(item);
        }
      });
      return res;
    },
    // 打开编辑面板
    openEdit(id) {
      this.showDialog = true;
      // 调用子组件中获取数据的方法
      this.$refs.mypanel.getPerData(id);
    }
  },
  components: {
    mypanel: () => import("./components/panel.vue")
  },
  created() {
    this.getAllPer();
  }
};
</script>

<style lang="scss">
.permission {
  margin: 20px;
  .btnbox {
    text-align: right;
  }
}
</style>
